package com.example.goodpet.utils;

import android.app.Activity;
import android.util.Log;

import com.example.goodpet.activity.SearchActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 统一应用程序中所有的Activity的栈管理
 * 涉及到activity的添加、删除指定、删除当前、删除所有、返回栈大小的方法
 */
public class ActivityManager {
    private String TAG=this.getClass().getSimpleName();
    private static Stack<Activity> activityStack=new Stack<>();
    private static List<Activity> searchActivityList=new ArrayList<>();
    private static List<Activity> searchResultActivity=new ArrayList<>();

    private static ActivityManager activityManager =new ActivityManager();

    private ActivityManager(){}

    public static ActivityManager getInstance(){
        return activityManager;
    }

    public void addActivity(Activity activity){
            activityStack.add(activity);
    }
    public void addSearchActivity(Activity activity){
//        Log.e(TAG, "addSearchActivity: "+ searchActivityList.size());

        if(searchActivityList.size()==2){
            Activity activity1 = searchActivityList.get(0);
            activity1.finish();
            searchActivityList.remove(activity1);
        }
        searchActivityList.add(activity);

    }
    public void addSearchResultActivity(Activity activity){
//        Log.e(TAG, "addSearchResultActivity: "+ searchResultActivity.size());
        if(searchResultActivity.size()!=0){
            for (Activity activity1 : searchResultActivity) {
                activity1.finish();
//                Log.e(TAG, "addSearchResultActivity: finish");
            }
            searchResultActivity.clear();
        }
        searchResultActivity.add(activity);

    }

    public void removeActivity(Activity activity){
        for(int i = activityStack.size() - 1; i >= 0 ; i--) {
        if(activityStack.get(i).getClass().equals(activity.getClass())){
            activity.finish();
            activityStack.remove(i);
            break;
        }
        }

    }

    public void removeCurrent(){
        Activity activity = activityStack.lastElement();
        activity.finish();
        activityStack.remove(activity);
    }
    public void removeListAt(int index){
        Activity activity = searchActivityList.get(index);
        activity.finish();
        searchActivityList.remove(activity);
    }

    public void removeAll(){
        for(int i = activityStack.size() - 1; i >= 0 ; i--) {
            activityStack.get(i).finish();
            activityStack.remove(i);
        }
    }


    public int size(){
        return activityStack.size();
    }
    public int searchActivitySize(){
        return searchActivityList.size();
    }

}
